﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter
{
	public abstract partial class UnitCommand
	{
		public string Name;
		abstract public float TimeRemaining { get; }
		public Unit Owner;
		public bool WasUserIssued = true;

		abstract protected float OnUpdate(float time);
		public bool IsStarted;
		public List<Activity> Activities = new List<Activity>();

		public float Update(float time)
		{
			if (!IsStarted)
			{
				IsStarted = true;
				_OnStarted();
			}
			for (int i = Activities.Count - 1; i >= 0; i--)
			{
				var a = Activities[i];
				bool hasCompleted = a.Update(Game.Instance.TimeDelta);
				if (hasCompleted)
				{
					Activities.RemoveAt(i);
				}
			}

			float timeUnused = OnUpdate(time);

			if (TimeRemaining <= 0)
			{
				_OnEnded();
			}
			return timeUnused;
		}

		virtual protected void _OnStarted()
		{
		}

		virtual protected void _OnEnded()
		{
			foreach (var a in Activities)
			{
				a.Abort();
			}
			Activities.Clear();
		}

		virtual public void Attach(Unit owner)
		{
			Owner = owner;
		}

		public void Abort()
		{
			_OnEnded();
		}
	}
}
